/**
 * @author jprieur
 */
package mygui;

import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.*;

import tui.*;
import utils.*;
import kernel.*;

public class ActionOpen extends AbstractAction
{
    MonIHM _gui;
		
    public ActionOpen (MonIHM gui){
	_gui = gui;
	putValue(AbstractAction.NAME,"Load");
	putValue(AbstractAction.SHORT_DESCRIPTION,"Load a snapshot");
	putValue(AbstractAction.ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_L,KeyEvent.CTRL_MASK ));
	putValue(AbstractAction.SMALL_ICON,UIM.createImageIcon("images/open.png","Load a snapshot"));
    }
		 
    public void actionPerformed(ActionEvent e) {
	JFileChooser fc = new JFileChooser();
	fc.setFileFilter(new SimmobilFileFilter("sim" + Simulator.getSimulator().getMode()));
	
	if(fc.showOpenDialog(_gui) == JFileChooser.APPROVE_OPTION){
	    Simulator kernel;
	    int old_mode = _gui._kernel.getMode();
	    if(old_mode == Simulator.SENSOR){
		kernel = new SensorSimulator(_gui, old_mode);
	    }else{
		kernel = new Simulator(_gui, old_mode);
	    }
	    
	    SAXParserFactory factory = SAXParserFactory.newInstance();
	    //factory.setValidating(true); // DTD check
	    // If we want to check with the DTD, the simmobil.dtd file has to be
	    // located near the file

	    try{
		SAXParser parser = factory.newSAXParser();
		if(old_mode != Simulator.SENSOR){
  		    parser.parse(fc.getSelectedFile(), new TuiContentHandler(kernel));
  		}
  		 else
  		{
  		    parser.parse(fc.getSelectedFile(), new TuiContentHandler((SensorSimulator)kernel));
  		}
	    } catch (SAXParseException spe) {
		// Error generated by the parser
		System.out.println("\n** Parsing error"
				   + ", line " + spe.getLineNumber()
				   + ", uri " + spe.getSystemId());
		System.out.println("   " + spe.getMessage() );
		// Use the contained exception, if any
		Exception  x = spe;
		if (spe.getException() != null)
		    x = spe.getException();
	    } catch (SAXException sxe) {
		// Error generated by this application
		// (or a parser-initialization error)
		Exception  x = sxe;
		if (sxe.getException() != null)
		    x = sxe.getException();
		x.printStackTrace();
	    } catch (ParserConfigurationException pce) {
		// Parser with specified options can't be built
		pce.printStackTrace();
	    } catch (IOException ioe){
		// I/O error
		ioe.printStackTrace();
	    }
	    _gui.setSimulator(kernel);
	    //System.out.println("voici le fichier choisis : " + (fc.getSelectedFile()).getAbsolutePath());
	    //MonIHM.openSnapshot(_gui,();
	}
	//_gui.informationPane.updateInfos();
	
    }
		

}
